/**
 * @name WsSdk v1.0.0
 * @author www.rxjy.com
 * @site https://www.rxjy.com
 * @license LGPL
 */
var WsSdk = {
    host: 'http://127.0.0.1:8081',
    base: 'https://chat.rxjy.com',
    ws: 'wss://chat.rxjy.com/ws',
    access_token: ''
}

/**
 * 解析url参数
 * @example ?id=12345&a=b
 * @return Object {id:12345, a:b}
 */
WsSdk.urlParse = function (search) {
    var url = search || window.location.search
    var obj = {}
    var reg = /[?&][^?&]+=[^?&]+/g
    var arr = url.match(reg)
    if (arr) {
        arr.forEach(function (item) {
            var tempArr = item.substr(1).split('=')
            var key = decodeURIComponent(tempArr[0])
            var val = decodeURIComponent(tempArr[1])
            obj[key] = val
        })
    }
    return obj
}

/**
 * 封装 ajax
 */
WsSdk.wxAjax = function (method, url, params, success, error) {
    params.access_token = WsSdk.access_token
    $.ajax({
        type: method,
        url: /^http(s*):\/\//.test(url) ? url : WsSdk.base + url,
        data: params,
        success: function (res) {
            if(typeof success === 'function') {
                success(res)
            }
        },
        error: function (err) {
            if(typeof error === 'function') {
                alert('请求错误，请重试...', err)
                error(error)
            }
        },
        complete: function () {
            // eslint-disable-next-line
            // console.log('....', WsSdk.access_token)
        }
    })
}

/**
 * 获取账号code
 */
WsSdk.app = function (params, callback) {
    WsSdk.wxAjax('get', 'https://piapi.rxjy.com/actionapi/CommonForeign/GetAppIDByCard', params, function (app) {
        if(app.StatusCode !== 0) {
            alert('登录失败')
            return false
        }
        WsSdk.token({
            client_id: 'chat-client',
            client_secret: 'chat-secret',
            grant_type: 'password',
            scope: 'select',
            username: app.Body.replace(/-/g, ''),
            password: '123456'
        }, function () {
            if(typeof callback === 'function') {
                callback()
            }
        })
    })
}

/**
 * 获取 token
 */
WsSdk.token = function (params, callback) {
    // debugger
    WsSdk.wxAjax('get', '/oauth/token', params, function (token) {
        WsSdk.access_token = token.access_token
        if(typeof callback === 'function') {
            callback()
        }
    })
}

/**
 * 查询聊天记录
 */
WsSdk.userMessage = function (params, callback) {
    return WsSdk.wxAjax('get', '/api/userMessage/findList', params, callback)
}

/**
 * 查询群组聊天记录
 */
WsSdk.groupMessage = function (params, callback) {
    return WsSdk.wxAjax('get', '/api/groupMessage/findList', params, callback)
}

/**
 * 开始初始化
 */
WsSdk.start = function (config) {
    /**
     * @name Chat v1.0.0
     * @author www.rxjy.com
     * @site https://www.rxjy.com
     * @license LGPL
     */
    if (!/^http(s*):\/\//.test(location.href)) {
        alert('请部署到localhost上查看该演示')
        return
    }
    if(config.card === undefined) {
        alert('登录人信息必传')
        return
    }

    layui.use(['layim', 'layer'], function() {
        var layim = layui.layim
        var layer = layui.layer
        var socket = null

        /**
         * WsSdk
         */
        WsSdk.app({
            card: config.card,
            postid: config.postid
        }, function () {
            layim.config({
                // 初始化接口
                init: {
                    url: WsSdk.base + '/api/user/init',
                    data: {
                        access_token: WsSdk.access_token
                    }
                },
                // 查看群员接口
                members: {
                    url: WsSdk.base + '/api/user/getMembers',
                    data: {
                        access_token: WsSdk.access_token
                    }
                },
                // 上传图片
                uploadImage: {
                    url: WsSdk.base + '/api/upload?access_token=' + WsSdk.access_token,
                    data: {
                        access_token: WsSdk.access_token
                    }
                },
                // 上传文件
                uploadFile: {
                    url: WsSdk.base + '/api/upload?access_token=' + WsSdk.access_token,
                    data: {
                        access_token: WsSdk.access_token
                    }
                },
                //主面板最小化后显示的名称
                title: WsSdk.card,
                // 是否开启桌面消息提醒，默认false
                notice: true,
                // 聊天记录页面地址，若不开启，剔除该项即可
                chatLog: layui.cache.dir + 'css/modules/layim/html/chatlog.html'
            })
        })

        /**
         * 监听layim建立就绪
         */
        layim.on('ready', function(res){
            Bind.screenshot()
            WsSocket.connection()
        })

        /**
         * 监听在线状态的切换事件
         */
        layim.on('online', function(data){
            console.log(data)
        })

        /**
         * 监听签名修改
         */
        layim.on('sign', function(value){
            console.log(value)
        })

        /**
         * 监听发送消息
         */
        layim.on('sendMessage', function(data){
            console.log(data)
            var file = /(img\[([^\s]+?)\])|(file\([\s\S]+?\)\[[\s\S]*?\])/g
            var message = {
                code: 2,
                message: {
                    username: data.mine.username,
                    avatar: data.mine.avatar,
                    id: data.to.id,
                    type: data.to.type === 'friend' ? 0 : 1,
                    content: data.mine.content,
                    cid: '',
                    mine: data.mine.mine,
                    fromid: data.mine.id,
                    timestamp: Date.now(),
                    msgType: file.test(data.mine.content) ? 102 : 2
                }
            }
            WsSocket.send(message)
        })

        /**
         * 监听查看群员
         */
        layim.on('members', function(data){
            console.log(data)
        })

        /**
         * 监听聊天窗口的切换
         */
        layim.on('chatChange', function(res){
            console.log(res)
        })

        /**
         * WsSocket
         */
        var WsSocket = {}
        WsSocket.heartCheck = function () {
            setInterval(function () {
                WsSocket.send({code: 0})
            }, 1000 * 55)
        }
        WsSocket.reload = function () {
            WsSdk.token(null, function () {
                WsSocket.connection()
            })
        }
        WsSocket.connection = function () {
            if(WsSdk.access_token === null && WsSdk.access_token === '已过期') {
                WsSocket.reload()
                return false
            }
            if('WebSocket' in window) {
                socket = new WebSocket(WsSdk.ws + '?token=' + WsSdk.access_token)
            }else {
                alert('该浏览器不支持本系统即时通讯功能，推荐使用谷歌或火狐浏览器！')
                return false
            }
            socket.onopen = function (event) {
                WsSocket.onopen(event)
            }
            socket.onerror = function (event) {
                WsSocket.onerror(event)
            }
            socket.onmessage = function (event) {
                WsSocket.onmessage(event)
            }
            socket.onclose = function (event) {
                WsSocket.onclose(event)
            }
        }
        WsSocket.onopen = function (value) {
            console.log('onopen', value)
            WsSocket.heartCheck()
            WsSocket.send({code: 1})
        }
        WsSocket.onerror = function (value) {
            console.log('onerror', value)
            WsSocket.connection()
        }
        WsSocket.onmessage = function (value) {
            console.log('onmessage', value)
            /* eslint-disable-next-line */
            var res = eval('(' + value.data + ')')
            if (res.code == 2) {
                var message = res.message
                var getmessage = {
                    username: message.username,
                    avatar: message.avatar,
                    id: message.type == 0 ? message.fromid : message.id,
                    type: message.type == 0 ?  'friend' : 'group',
                    content: message.content,
                    cid: message.cid,
                    mine: message.mine,
                    fromid: message.fromid,
                    timestamp: new Date(message.timestamp).getFullYear() === 1970 ? message.timestamp * 1000 : message.timestamp
                }
                layim.getMessage(getmessage)
            }else if (res.code == 3) {
                layim.setFriendStatus(res.friendId, res.status)
            }
        }
        WsSocket.onclose = function (value) {
            console.log('onclose', value)
        }
        WsSocket.send = function (value) {
            if(socket.readyState === 1) {
                socket.send(JSON.stringify(value))
            } else {
                WsSocket.connection()
            }
        }
        WsSocket.close = function (value) {
            socket.close(value)
        }

        /**
         * Bind
         */
        var Bind = {}
        Bind.screenshot = function () {
            var imgReader = function (item) {
                var blob = item.getAsFile()
                var formData = new FormData()
                var reader = new FileReader()
                reader.onload = function (e) {
                    var imgSrc = e.target.result
                    layer.confirm('<img src="' + imgSrc + '">', {title: '发送截图', offset: ['50px', '50px']}, function (index) {
                        formData.append('file', blob)
                        $.ajax({
                            url: WsSdk.base + '/api/upload?access_token=' + WsSdk.access_token,
                            type: 'post',
                            data: formData,
                            processData: false,
                            contentType: false,
                            success: function (result) {
                                if(result.code === 0) {
                                    $('.layim-chat-textarea textarea').val('img[' + result.data.src + ']')
                                    $('.layim-send-btn').click()
                                }else {
                                    layer.alert(result.msg)
                                }
                            }
                        })
                        layer.close(index)
                    })
                }
                reader.readAsDataURL(blob)
            }
            try {
                $('body').unbind('paste', '.layim-chat-textarea textarea').bind('paste', '.layim-chat-textarea textarea', function (e) {
                    var clipboardData = event.clipboardData || window.clipboardData || event.originalEvent.clipboardData
                    var i = 0, items, item, types
                    if (clipboardData) {
                        items = clipboardData.items
                        if (!items) {
                            return
                        }
                        item = items[0]
                        types = clipboardData.types || []
                        for (var i = 0; i < types.length; i++) {
                            if (types[i] === 'Files') {
                                item = items[i]
                                break
                            }
                        }
                        if (item && item.kind === 'file' && item.type.match(/^image\//i)) {
                            imgReader(item)
                        }
                    }
                })
            } catch (e) {
                console.log(e)
            }
        }
    })
}
